<template>
  <el-form :inline="true">
    <el-form-item label="一级分类">
      <el-select
        placeholder="请选择"
        v-model="category.category1Id"
        :disabled="disabled">
        <el-option
          :label="c1.name"
          :value="c1.id"
          v-for="c1 in category.category1List"
          :key="c1.id" />
      </el-select>
    </el-form-item>
    <el-form-item label="二级分类">
      <el-select
        placeholder="请选择"
        v-model="category.category2Id"
        :disabled="disabled">
        <el-option
          :label="c2.name"
          :value="c2.id"
          v-for="c2 in category.category2List"
          :key="c2.id" />
      </el-select>
    </el-form-item>
    <el-form-item label="三级分类">
      <el-select
        placeholder="请选择"
        v-model="category.category3Id"
        :disabled="disabled">
        <el-option
          :label="c3.name"
          :value="c3.id"
          v-for="c3 in category.category3List"
          :key="c3.id" />
      </el-select>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "CategoryList",
});
</script>

<script setup lang="ts">
import categoryStore from "@/stores/category";
import { onBeforeMount, onMounted, onUnmounted, watch } from "vue";

defineProps<{
  disabled: boolean;
}>();

const category = categoryStore();

onBeforeMount(() => {
  categoryStore().removeCategory();
});

onMounted(() => {
  category.getCategory1List();
  categoryStore().removeCategory();
});

// 监视category.category1Id的变化
// category是一个Proxy对象
// category1Id属性在category中本质是一个ref对象
// 注意: 当读取proxy对象中的一个ref对象属性时, 它会自动读取返回其value值
//    不能直接watch, 得使用函数的形式
watch(
  () => category.category1Id,
  async (val) => {
    // console.log(val);
    // category.getCategory2List(val as number);
    if (val) {
      category.getCategory2List(val);
    }
  }
);

watch(
  () => category.category2Id,
  async (val) => {
    if (val) {
      category.getCategory3List(val);
    }
  }
);
</script>
